package com.dreamer.view.pmall;

import com.dreamer.domain.pmall.goods.PmallGoods;
import com.dreamer.domain.pmall.goods.PmallGoodsType;
import com.dreamer.domain.pmall.order.Order;
import com.dreamer.domain.pmall.order.OrderItem;
import com.dreamer.domain.user.Accounts;
import com.dreamer.domain.user.AddressMy;
import com.dreamer.domain.user.Agent;
import com.dreamer.domain.user.User;
import com.dreamer.domain.wechat.WxConfig;
import com.dreamer.service.mobile.*;
import com.dreamer.service.mobile.factory.WxConfigFactory;
import com.dreamer.upload.util.StringUtil;
import com.wxjssdk.JSAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import ps.mx.otter.utils.WebUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping(value = {"/pmall/shopcart", "/dmz/pmall/shopcart"})
public class PmallShopCartQueryController {


    //购物车
    @RequestMapping(value = "/index.html", method = RequestMethod.GET)
    public String addGoodsToShopcart(
            HttpServletRequest request, Model model) {
        return "pmall/shopcart/index";
    }

    //提交订单
    @RequestMapping(value = "/commit.html")
    public String commit(HttpServletRequest request, Model model) {
        User user = (User) WebUtil.getCurrentUser(request);
        Agent agent = agentHandler.get(user.getId());
        model.addAttribute("agent", agent);
        //地址
        List<AddressMy> addressMyList = addressMyHandler.findAddressByAgent(agent);
        model.addAttribute("addressMyList", addressMyList);
        return "pmall/shopcart/commit";
    }

    //去支付
    @RequestMapping(value = "/pay.html")
    public String pay(HttpServletRequest request, Model model, String id) {
//        User user = (User) WebUtil.getCurrentUser(request);
//        Agent agent = agentHandler.get(user.getId());
//        //获取订单
//        Order order = orderHandler.get(Integer.valueOf(id));
//        if (order == null) {
//            model.addAttribute("message", "订单不存在!");
//            return "mobile/error";
//        }
//        //没有支付的openid 就去获取
//        WxConfig wxConfig = wxConfigFactory.getBaseConfig();
//        WxConfig payConfig = wxConfigFactory.getPayConfig();
//        String openid = agent.getWxOpenid();
//        if(payConfig.getOpen()){
//            if (StringUtil.isBlank(agent.getPayOpenid())) {//如果支付的openid为空 跳转到获取code的地址
//                String redirectUrl = ServletUriComponentsBuilder.fromContextPath(request).path("/pmall/shopcart/callBack.html").build().toString();
//                String url = JSAPI.createGetCodeUrl(payConfig.getAppid(), redirectUrl, "snsapi_base", id);
//                return "redirect:" + url;
//            }else {
//                wxConfig = payConfig;
//                openid = agent.getPayOpenid();
//            }
//        }
//
//        //去支付
//        String jsApiParam = payHandler.toWxPay(wxConfig, openid, order.getOrderNo(), order.getAmount(),WxConfig.PMALL_NOTICE_URL);
//        model.addAttribute("jsApiParam", jsApiParam);
//        model.addAttribute("agent", agent);
//        model.addAttribute("order", order);
//        return "pmall/shopcart/pay";

        //todo 这里将微信支付暂时改为代金券支付
        User user = (User) WebUtil.getCurrentUser(request);
        Agent agent = agentHandler.get(user.getId());
        Order order = orderHandler.get(Integer.valueOf(id));
        if (order == null) {
            model.addAttribute("message", "订单不存在!");
            return "mobile/error";
        }
        model.addAttribute("order", order);
        model.addAttribute("agent", order.getUser());

        //TODO 保存套餐
        List<PmallGoods> pmallGoodsList = new ArrayList<>();

        //TODO 获取当前订单 ------判断当前订单是不是套餐订单
        Set<OrderItem> orderItemSet = order.getItems();
        if(orderItemSet != null){
            for(OrderItem orderItem : orderItemSet){
                PmallGoods pmallGoods = orderItem.getPmallGoods();
                if(pmallGoods != null){
                    PmallGoodsType pmallGoodsType = pmallGoods.getGoodsType();
                    if(pmallGoodsType != null){
                        if(pmallGoodsType.getId()==15 || pmallGoodsType.getName().equals("代理套餐")){
                            pmallGoodsList.add(pmallGoods);
                        }
                    }
                }
            }
        }
        model.addAttribute("pmallGoodsList",pmallGoodsList);

        //TODO 保存代理专享
        List<PmallGoods> pgList = new ArrayList<>();

        //TODO 获取当前订单 ------判断当前订单是不是代理专享订单
        Set<OrderItem> ios = order.getItems();
        if(ios != null){
            for(OrderItem oi : ios){
                PmallGoods pg = oi.getPmallGoods();
                if(pg != null){
                    PmallGoodsType pgt = pg.getGoodsType();
                    if(pgt != null){
                        if(pgt.getId()==24 || pgt.getName().equals("代理专享")){
                            pgList.add(pg);
                        }
                    }
                }
            }
        }
        model.addAttribute("pgList",pgList);


//        Accounts accounts = accountsHandler.get(agent.getId());
//        Double value1 = accounts.getVoucherBalance();
//        Double value2 = order.getAmount();
//        if(value1 > value2){
//            model.addAttribute("message", "代金券不足!");
//            return "mobile/error";
//        }else{
//            Double value3 = value1 - value2;
//            accounts.setVoucherBalance(value3);
//            accountsHandler.merge(accounts);
//        }
        return "pmall/shopcart/pay";
    }

    @Autowired
    private AccountsHandler accountsHandler;


    //获取用户支付的id 再去支付
//    @RequestMapping("/callBack.html")
//    public String resetOpenIdPay(String code, String state, HttpServletRequest request, Model model) {
//        String jsApiParam ="";
//        try {// TODO 这里要捕获异常 但是总是抛出一个莫名其妙的异常
////            System.out.println("callBack支付页面");
//            jsApiParam = orderHandler.resetOpenIdToPay(code, state);
//
//        } catch (Exception e) {
////            e.printStackTrace();
////            model.addAttribute("message", e.getMessage());
////            return "mobile/error";
//            System.out.println("下单异常" + e.getMessage());
//        }
//        Order order = orderHandler.get(Integer.valueOf(state));
//        model.addAttribute("jsApiParam", jsApiParam);
//        model.addAttribute("agent", order.getUser());
//        model.addAttribute("order", order);
//        return "pmall/shopcart/pay";
//
//    }


    @Autowired
    private OrderHandler orderHandler;

    @Autowired
    private AgentHandler agentHandler;

    @Autowired
    private AddressMyHandler addressMyHandler;

    @Autowired
    private PayHandler payHandler;

    @Autowired
    private WxConfigFactory wxConfigFactory;

    private final Logger LOG = LoggerFactory.getLogger(getClass());
}
